package com.maodou.android.ui.page.main

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.LayoutDirection
import com.maodou.android.ui.page.home.HomeScreen
import com.maodou.android.ui.page.mine.MineScreen
import kotlinx.coroutines.launch

@Composable
fun MainScreen() {
    val tabs = listOf("首页")
    val pagerState = rememberPagerState(initialPage = 0) { tabs.size }
    val scope = rememberCoroutineScope()

    // 保存每个页面的可滚动状态（跨重组/切页保持）
    val homeListState: LazyListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState(0, 0) }
    val mineScrollState: ScrollState = rememberSaveable(saver = ScrollState.Saver) { ScrollState(0) }

    // 页面内部 rememberSaveable 的状态保存（页面被回收后恢复）
    val saveableStateHolder = rememberSaveableStateHolder()

    // 未读角标/红点
    val homeUnread by rememberSaveable { mutableStateOf(12) }
    val mineHasDot by rememberSaveable { mutableStateOf(true) }

    // 双击 Tab 回到顶部判定
    var lastClickTime by remember { mutableLongStateOf(0L) }
    var lastClickIndex by remember { mutableIntStateOf(-1) }
    val doubleTapThresholdMs = 300L

    fun scrollCurrentTabToTop(index: Int) {
        scope.launch {
            when (index) {
                0 -> homeListState.animateScrollToItem(0)
                1 -> mineScrollState.animateScrollTo(0)
            }
        }
    }

    val navItemColors = NavigationBarItemDefaults.colors(
        selectedIconColor = MaterialTheme.colorScheme.primary,
        selectedTextColor = MaterialTheme.colorScheme.primary,
        unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
        unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant,
        indicatorColor = MaterialTheme.colorScheme.secondaryContainer
    )

    Scaffold(
        bottomBar = {
//            NavigationBar {
//                tabs.forEachIndexed { index, title ->
//                    val selected = pagerState.currentPage == index
//                    NavigationBarItem(
//                        selected = selected,
//                        onClick = {
//                            val now = System.currentTimeMillis()
//                            if (selected) {
//                                // 双击回到顶部
//                                if (lastClickIndex == index && now - lastClickTime <= doubleTapThresholdMs) {
//                                    scrollCurrentTabToTop(index)
//                                }
//                                lastClickTime = now
//                                lastClickIndex = index
//                            } else {
//                                scope.launch { pagerState.scrollToPage(index) }
//                                lastClickTime = now
//                                lastClickIndex = index
//                            }
//                        },
//                        icon = {
//                            BadgedBox(
//                                badge = {
//                                    when (index) {
//                                        0 -> if (homeUnread > 0) {
//                                            Badge { Text(text = if (homeUnread > 99) "99+" else "$homeUnread") }
//                                        }
//                                        1 -> if (mineHasDot) {
//                                            Badge {} // 仅红点
//                                        }
//                                    }
//                                }
//                            ) {
//                                if (index == 0) {
//                                    Icon(
//                                        imageVector = if (selected) Icons.Filled.Home else Icons.Outlined.Home,
//                                        contentDescription = title
//                                    )
//                                } else {
//                                    Icon(
//                                        imageVector = if (selected) Icons.Filled.Person else Icons.Outlined.Person,
//                                        contentDescription = title
//                                    )
//                                }
//                            }
//                        },
//                        label = { Text(title) },
//                        colors = navItemColors
//                    )
//                }
//            }
        }
    ) { innerPadding ->
        HorizontalPager(
            state = pagerState,
            modifier = Modifier
                .fillMaxSize()
                .padding(bottom = innerPadding.calculateBottomPadding())
        ) { page ->
            when (page) {
                0 -> saveableStateHolder.SaveableStateProvider(key = "home") {
                    HomeScreen(listState = homeListState)
                }
                else -> saveableStateHolder.SaveableStateProvider(key = "mine") {
                    MineScreen(scrollState = mineScrollState)
                }
            }
        }
    }
}

@Preview(showBackground = true, widthDp = 360, heightDp = 640)
@Composable
fun MainScreenPreview() {
    MainScreen()
}